package ciicos.check.service.impl;

import ciicos.base.model.filter.RuleInfo;
import ciicos.check.entity.*;
import ciicos.check.mapper.CheckTaskMapper;
import ciicos.check.model.checktask.CheckTaskForm;
import ciicos.check.model.checktask.CheckTaskPagination;
import ciicos.check.service.*;
import ciicos.iview.service.IviewService;
import ciicos.model.visiual.superQuery.ConditionJsonModel;
import ciicos.model.visiual.superQuery.SuperQueryConditionModel;
import ciicos.model.visiual.superQuery.SuperQueryJsonModel;
import ciicos.permission.model.authorize.AuthorizeConditionModel;
import ciicos.permission.service.AuthorizeService;
import ciicos.permission.util.GenUtil;
import ciicos.point.result.ScadaEntity;
import ciicos.point.result.ScadaResult;
import ciicos.util.*;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 巡检任务
 * 版本： V3.2.0
 * 版权：
 * 作者： 产研项目租
 * 日期： 2023-07-26
 */
@Slf4j
@Service
public class CheckTaskServiceImpl extends ServiceImpl<CheckTaskMapper, CheckTaskEntity> implements CheckTaskService {


    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private AuthorizeService authorizeService;


    @Autowired
    private CheckTaskItemService checkTaskItemService;

    @Autowired
    private CheckPlanService checkPlanService;

    @Autowired
    private CheckPlanItemService checkPlanItemService;

    @Autowired
    private CheckPlanTimeService checkPlanTimeService;

    @Autowired
    private CheckTaskService checkTaskService;

    @Autowired
    private IviewService iviewService;

    @Override
    public List<CheckTaskEntity> getList(CheckTaskPagination checkTaskPagination) {
        return getTypeList(checkTaskPagination, checkTaskPagination.getDataType());
    }

    @Override
    public List<CheckTaskEntity> getTypeList(CheckTaskPagination checkTaskPagination, String dataType) {
        String userId = userProvider.get().getUserId();
        List<String> AllIdList = new ArrayList();
        List<List<String>> intersectionList = new ArrayList<>();
        int total = 0;
        int checkTaskNum = 0;
        QueryWrapper<CheckTaskEntity> checkTaskQueryWrapper = new QueryWrapper<>();
        List<String> currentDay = generaterSwapUtil.getCurrentDay(new Date());
        checkTaskQueryWrapper.lambda().between(checkTaskPagination.getFlag() == 1, CheckTaskEntity::getCreatortime, currentDay.get(0), currentDay.get(1));
        // 查询历史任务
        if (checkTaskPagination.getFlag() == 2) {
            // 今天
            LocalDate now = LocalDate.now();
            System.out.println(now);
            // 一个月之前
            LocalDate minusDays = now.minusMonths(1);
            System.out.println(minusDays);
            checkTaskQueryWrapper.lambda().between(CheckTaskEntity::getCreatortime, minusDays, now);
        }

        int checkTaskItemNum = 0;
        QueryWrapper<CheckTaskItemEntity> checkTaskItemQueryWrapper = new QueryWrapper<>();


        //树形，异步父级查询条件
        long checkTaskItemcount = checkTaskItemService.count();
        List<String> allSuperIDlist = new ArrayList<>();
        String superOp = "";
        if (ObjectUtil.isNotEmpty(checkTaskPagination.getSuperQueryJson())) {
            SuperQueryJsonModel superQueryJsonModel = JsonUtil.getJsonToBean(checkTaskPagination.getSuperQueryJson(), SuperQueryJsonModel.class);
            String matchLogic = superQueryJsonModel.getMatchLogic();
            List<ConditionJsonModel> superQueryList = JsonUtil.getJsonToList(superQueryJsonModel.getConditionJson(), ConditionJsonModel.class);
            for (ConditionJsonModel conditionjson : superQueryList) {
                Map<String, Object> map = JsonUtil.stringToMap(conditionjson.getAttr());
                Map<String, Object> configMap = JsonUtil.stringToMap(map.get("__config__").toString());
                String tableName = configMap.get("relationTable") != null ? String.valueOf(configMap.get("relationTable")) : String.valueOf(configMap.get("tableName"));
                if (map.get("multiple") != null) {
                    if (Boolean.valueOf(String.valueOf(map.get("multiple"))) && ObjectUtil.isNull(conditionjson.getFieldValue())) {
                        conditionjson.setFieldValue("[]");
                    }
                }
                conditionjson.setTableName(tableName);
            }
            List<String> allSuperList = new ArrayList<>();
            List<List<String>> intersectionSuperList = new ArrayList<>();


            int checkTaskNum1 = 0;
            QueryWrapper<CheckTaskEntity> checkTaskSuperWrapper = new QueryWrapper<>();
            checkTaskNum1 = generaterSwapUtil.getCondition(new SuperQueryConditionModel(checkTaskSuperWrapper, superQueryList, matchLogic, "check_task")
                    , new CheckTaskEntity(), checkTaskNum1);
            if (checkTaskNum1 > 0) {
                List<String> checkTaskList = this.list(checkTaskSuperWrapper).stream().map(CheckTaskEntity::getId).collect(Collectors.toList());
                allSuperList.addAll(checkTaskList);
                intersectionSuperList.add(checkTaskList);
            }
            int checkTaskItemNum1 = 0;
            QueryWrapper<CheckTaskItemEntity> checkTaskItemSuperWrapper = new QueryWrapper<>();
            checkTaskItemNum1 = generaterSwapUtil.getCondition(new SuperQueryConditionModel(checkTaskItemSuperWrapper, superQueryList, matchLogic, "check_task_item")
                    , new CheckTaskItemEntity(), checkTaskItemNum1);
            if (checkTaskItemNum1 > 0 && checkTaskItemcount > 0) {

                List<String> checkTaskItemList = checkTaskItemService.list(checkTaskItemSuperWrapper).stream().map(CheckTaskItemEntity::getParentid).collect(Collectors.toList());
                allSuperList.addAll(checkTaskItemList);
                intersectionSuperList.add(checkTaskItemList);
            }
            superOp = matchLogic;
            //and or
            if (matchLogic.equalsIgnoreCase("and")) {
                allSuperIDlist = generaterSwapUtil.getIntersection(intersectionSuperList);
            } else {
                allSuperIDlist = allSuperList;
            }
        }
        boolean pcPermission = true;
        boolean appPermission = true;
        boolean isPc = ServletUtil.getHeader("ciicos-origin").equals("pc");
        if (isPc && pcPermission) {
            if (!userProvider.get().getIsAdministrator()) {
                Object checkTaskObj = authorizeService.getCondition(new AuthorizeConditionModel(checkTaskQueryWrapper, checkTaskPagination.getMenuId(), "check_task"));
                if (ObjectUtil.isEmpty(checkTaskObj)) {
                    return new ArrayList<>();
                } else {
                    checkTaskQueryWrapper = (QueryWrapper<CheckTaskEntity>) checkTaskObj;
                    if (checkTaskQueryWrapper.getExpression().getNormal().size() > 0) {
                        checkTaskNum++;
                    }
                }
                Object checkTaskItemObj = authorizeService.getCondition(new AuthorizeConditionModel(checkTaskItemQueryWrapper, checkTaskPagination.getMenuId(), "check_task_item"));
                if (ObjectUtil.isEmpty(checkTaskItemObj)) {
                    return new ArrayList<>();
                } else {
                    checkTaskItemQueryWrapper = (QueryWrapper<CheckTaskItemEntity>) checkTaskItemObj;
                    if (checkTaskItemQueryWrapper.getExpression().getNormal().size() > 0) {
                        checkTaskItemNum++;
                    }
                }
            }
        }


        if (ObjectUtil.isNotEmpty(checkTaskPagination.getPlancode())) {
            checkTaskNum++;

            checkTaskQueryWrapper.lambda().like(CheckTaskEntity::getPlancode, checkTaskPagination.getPlancode());

        }

        if (ObjectUtil.isNotEmpty(checkTaskPagination.getPlanname())) {
            checkTaskNum++;

            checkTaskQueryWrapper.lambda().like(CheckTaskEntity::getPlanname, checkTaskPagination.getPlanname());

        }

        if (ObjectUtil.isNotEmpty(checkTaskPagination.getCode())) {
            checkTaskNum++;

            checkTaskQueryWrapper.lambda().like(CheckTaskEntity::getCode, checkTaskPagination.getCode());

        }

        if (ObjectUtil.isNotEmpty(checkTaskPagination.getCheckteam())) {
            checkTaskNum++;
            checkTaskQueryWrapper.lambda().in(CheckTaskEntity::getCheckteam, checkTaskPagination.getCheckteam());

        }

        if (ObjectUtil.isNotEmpty(checkTaskPagination.getConfirmuserid())) {
            checkTaskNum++;
            checkTaskQueryWrapper.lambda().in(CheckTaskEntity::getConfirmuserid, checkTaskPagination.getConfirmuserid());
        }

        if (ObjectUtil.isNotEmpty(checkTaskPagination.getConfirmresult())) {
            checkTaskNum++;

            List<String> idList = new ArrayList<>();
            try {
                String[][] confirmresult = JsonUtil.getJsonToBean(checkTaskPagination.getConfirmresult(), String[][].class);
                for (int i = 0; i < confirmresult.length; i++) {
                    if (confirmresult[i].length > 0) {
                        idList.add(confirmresult[i][confirmresult[i].length - 1]);
                    }
                }
            } catch (Exception e1) {
                try {
                    List<String> confirmresult = JsonUtil.getJsonToList(checkTaskPagination.getConfirmresult(), String.class);
                    if (confirmresult.size() > 0) {
                        idList.add(confirmresult.get(confirmresult.size() - 1));
                    }
                } catch (Exception e2) {
                    idList.add(String.valueOf(checkTaskPagination.getConfirmresult()));
                }
            }
            checkTaskQueryWrapper.lambda().and(t -> {
                idList.forEach(tt -> {
                    t.like(CheckTaskEntity::getConfirmresult, tt).or();
                });
            });

        }

        if (ObjectUtil.isNotEmpty(checkTaskPagination.getStatus())) {
            checkTaskNum++;

            List<String> idList = new ArrayList<>();
            try {
                String[][] status = JsonUtil.getJsonToBean(checkTaskPagination.getStatus(), String[][].class);
                for (int i = 0; i < status.length; i++) {
                    if (status[i].length > 0) {
                        idList.add(status[i][status[i].length - 1]);
                    }
                }
            } catch (Exception e1) {
                try {
                    List<String> status = JsonUtil.getJsonToList(checkTaskPagination.getStatus(), String.class);
                    if (status.size() > 0) {
                        idList.add(status.get(status.size() - 1));
                    }
                } catch (Exception e2) {
                    idList.add(String.valueOf(checkTaskPagination.getStatus()));
                }
            }
            checkTaskQueryWrapper.lambda().and(t -> {
                idList.forEach(tt -> {
                    t.like(CheckTaskEntity::getStatus, tt).or();
                });
            });

        }

        if (checkTaskItemNum > 0) {
            List<String> checkTaskItemIdList = checkTaskItemService.list(checkTaskItemQueryWrapper).stream().filter(t -> StringUtil.isNotEmpty(t.getParentid())).map(t -> t.getParentid()).collect(Collectors.toList());
            long count = checkTaskItemService.count();
            if (count > 0) {
                intersectionList.add(checkTaskItemIdList);
            }
            AllIdList.addAll(checkTaskItemIdList);
        }
        total += checkTaskItemNum;
        List<String> intersection = generaterSwapUtil.getIntersection(intersectionList);
        if (total > 0) {
            if (intersection.size() == 0) {
                intersection.add("jnpfNullList");
            }
            checkTaskQueryWrapper.lambda().in(CheckTaskEntity::getId, intersection);
        }
        //是否有高级查询
        if (StringUtil.isNotEmpty(superOp)) {
            if (allSuperIDlist.size() == 0) {
                allSuperIDlist.add("jnpfNullList");
            }
            List<String> finalAllSuperIDlist = allSuperIDlist;
            checkTaskQueryWrapper.lambda().and(t -> t.in(CheckTaskEntity::getId, finalAllSuperIDlist));
        }


        //排序
        if (StringUtil.isEmpty(checkTaskPagination.getSidx())) {
            checkTaskQueryWrapper.lambda().orderByDesc(CheckTaskEntity::getId);
        } else {
            try {
                String sidx = checkTaskPagination.getSidx();
                CheckTaskEntity checkTaskEntity = new CheckTaskEntity();
                Field declaredField = checkTaskEntity.getClass().getDeclaredField(sidx);
                declaredField.setAccessible(true);
                String value = declaredField.getAnnotation(TableField.class).value();
                checkTaskQueryWrapper = "asc".equals(checkTaskPagination.getSort().toLowerCase()) ? checkTaskQueryWrapper.orderByAsc(value) : checkTaskQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
        // 过滤条件

        if ("0".equals(dataType)) {
            if ((total > 0 && AllIdList.size() > 0) || total == 0) {
                Page<CheckTaskEntity> page = new Page<>(checkTaskPagination.getCurrentPage(), checkTaskPagination.getPageSize());
                IPage<CheckTaskEntity> userIPage = this.page(page, checkTaskQueryWrapper);
                return checkTaskPagination.setData(userIPage.getRecords(), userIPage.getTotal());
            } else {
                List<CheckTaskEntity> list = new ArrayList();
                return checkTaskPagination.setData(list, list.size());
            }
        } else {
            return this.list(checkTaskQueryWrapper);
        }
    }

    public QueryWrapper wrapperHandle(QueryWrapper<?> wrapper, String id, Class<?> aClass, String type, String tableName) {
        try {
            // 避免空and
            wrapper.apply(" 1=1 ");
            List<RuleInfo> ruleInfos = generaterSwapUtil.getFilterCondition(id);
            for (RuleInfo info : ruleInfos) {
                String field = info.getField();
                if ("main".equals(type) && field.contains("-")) {
                    continue;
                }
                if ("main".equals(type) && field.contains("_jnpf_")) {
                    continue;
                }
                if ("sub".equals(type) && !field.contains("-")) {
                    continue;
                }
                if ("sub-jnpf".equals(type) && !field.contains("_jnpf_")) {
                    continue;
                }
                String fieldName = field;
                String table = "";
                if (field.contains("-")) {
                    fieldName = field.split("-")[1];
                }
                if (field.contains("_jnpf_")) {
                    fieldName = field.split("_jnpf_")[1];
                    table = field.split("_jnpf_")[0];
                    table = table.replace("jnpf_", "");
                }
                if ("sub-jnpf".equals(type) && !tableName.equals(table)) {
                    continue;
                }
                Field declaredField = aClass.getDeclaredField(fieldName);
                declaredField.setAccessible(true);
                String fieldDb = declaredField.getAnnotation(TableField.class).value();
                GenUtil genUtil = JsonUtil.getJsonToBean(info, GenUtil.class);
                genUtil.solveValue(wrapper, fieldDb);
            }
            return wrapper;
        } catch (Exception e) {
            return wrapper;
        }
    }

    @Override
    public CheckTaskEntity getInfo(String id) {
        QueryWrapper<CheckTaskEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CheckTaskEntity::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    public void create(CheckTaskEntity entity) {
        this.save(entity);
    }

    @Override
    public boolean update(String id, CheckTaskEntity entity) {
        return this.updateById(entity);
    }

    @Override
    public void delete(CheckTaskEntity entity) {
        if (entity != null) {
            this.removeById(entity.getId());
        }
    }

    //子表方法
    @Override
    public List<CheckTaskItemEntity> getCheckTaskItemList(String id, CheckTaskPagination checkTaskPagination) {
        QueryWrapper<CheckTaskItemEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper = checkTaskItemService.getChild(checkTaskPagination, queryWrapper);
        queryWrapper.lambda().eq(CheckTaskItemEntity::getParentid, id);
        queryWrapper.lambda().orderByAsc(CheckTaskItemEntity::getSortcode);
        this.wrapperHandle(queryWrapper, checkTaskPagination.getModuleId(), CheckTaskItemEntity.class, "sub", "checkTaskItem");
        return checkTaskItemService.list(queryWrapper);
    }

    @Override
    public List<CheckTaskItemEntity> getCheckTaskItemList(String id) {
        QueryWrapper<CheckTaskItemEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CheckTaskItemEntity::getParentid, id);
        // queryWrapper.lambda().orderByAsc(CheckTaskItemEntity::getSortcode);
        return checkTaskItemService.list(queryWrapper);
    }

    //列表子表数据方法


    //验证表单唯一字段
    @Override
    public String checkForm(CheckTaskForm form, int i) {
        int total = 0;
        boolean isUp = StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
        String id = "";
        String countRecover = "";
        if (isUp) {
            id = form.getId();
        }
        if (form.getCheckTaskItemList() != null) {
        }

        return countRecover;
    }

    @Override
    public void createTask() {
        log.info("------开始生成今日任务");
        //先判断昨日是否有逾期的
        late();

        //查询启用的计划
        List<CheckPlanEntity> planEntityList = checkPlanService.getListByEnable();
        if (planEntityList != null && planEntityList.size() > 0) {
            LocalDate today = LocalDate.now();
            //需要处理的数据
            List<Map<String, Object>> paramList = new ArrayList<>();

            for (CheckPlanEntity planEntity : planEntityList) {
                log.info("计划编码：{}", planEntity.getCode());
                List<CheckPlanTimeEntity> checkPlanTimeList = new ArrayList<>();
                //定时配置
                List<CheckPlanTimeEntity> planTimeList = checkPlanService.getCheckPlanTimeList(planEntity.getId());
                if (planTimeList != null && planTimeList.size() > 0) {
                    for (CheckPlanTimeEntity checkPlanTimeEntity : planTimeList) {
                        //筛选出需要生成的定时配置项
                        if (isTaskScheduledForToday(checkPlanTimeEntity, today)) {
                            checkPlanTimeList.add(checkPlanTimeEntity);
                        }
                    }
                    //巡检项配置
                    List<CheckPlanItemEntity> checkPlanItemList = checkPlanService.getCheckPlanItemList(planEntity.getId());
                    Map<String, Object> param = new HashMap<>();
                    param.put("plan", planEntity);
                    param.put("items", checkPlanItemList);
                    param.put("times", checkPlanTimeList);
                    paramList.add(param);

                } else {
                    log.info("未配置定时配置");
                }
            }
            //创建数据
            if (paramList.size() > 0) {
                createTaskForToday(paramList);
            }
        } else {
            log.info("未配置计划");
        }
        log.info("------今日任务生成完成");
    }

    private void late() {
        Date dayBegin = DateUtil.getBeginDayOfYesterday();
        Date dayEnd = DateUtil.getEndDayOfYesterday();

        //获取昨日生成的任务
        List<CheckTaskEntity> list = list(new LambdaQueryWrapper<CheckTaskEntity>()
                .gt(CheckTaskEntity::getCreatortime, dayBegin)
                .lt(CheckTaskEntity::getCreatortime, dayEnd));
        if (list != null && list.size() != 0) {
            for (CheckTaskEntity checkTaskEntity : list) {
                if (!"2".equals(checkTaskEntity.getStatus())) {
                    checkTaskEntity.setStatus("1");
                    updateById(checkTaskEntity);
                }
            }
        }

    }

    @Override
    public List<CheckTaskEntity> getAllCheckTaskBetweenDate(String orgcode, Date begintime, Date endtime) {

        LambdaQueryWrapper<CheckTaskEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.ge(CheckTaskEntity::getTaskstarttime, begintime);
        wrapper.le(CheckTaskEntity::getTaskendtime, endtime);
        wrapper.orderByAsc(CheckTaskEntity::getTaskstarttime);
        wrapper.eq(StringUtil.isNotEmpty(orgcode), CheckTaskEntity::getCheckteam, orgcode);

        return this.list(wrapper);
    }

    @Override
    public List<CheckTaskEntity> getCheckTaskBetweenDateWithStatus(String orgcode, Date begintime, Date endtime) {
        LambdaQueryWrapper<CheckTaskEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.ge(CheckTaskEntity::getRealstarttime, begintime);
        wrapper.le(CheckTaskEntity::getRealendtime, endtime);
        wrapper.orderByAsc(CheckTaskEntity::getTaskstarttime);
        wrapper.in(CheckTaskEntity::getStatus, 1, 2);
        wrapper.eq(StringUtil.isNotEmpty(orgcode), CheckTaskEntity::getCheckteam, orgcode);

        return this.list(wrapper);
    }

    @Override
    public List<CheckTaskEntity> getListByPlanCode(String code) {

        return this.list(
                new LambdaQueryWrapper<CheckTaskEntity>()
                        .eq(CheckTaskEntity::getPlancode, code)
                        .in(CheckTaskEntity::getStatus, 0, 1)
        );
    }

    @Override
    public List<CheckTaskItemEntity> syncRealDataPointValues(String id) {

        //获取任务下巡检项-设备点位
        List<CheckTaskItemEntity> checkTaskPoints = checkTaskItemService.list(new LambdaQueryWrapper<CheckTaskItemEntity>()
                .eq(CheckTaskItemEntity::getParentid, id)
                .eq(CheckTaskItemEntity::getType, "1"));

        if (checkTaskPoints != null && checkTaskPoints.size() > 0) {

            for (CheckTaskItemEntity entity : checkTaskPoints) {
                String realdata = iviewService.realdata(null, entity.getPointName(), "NAME,Kind,Desc,PV,ALMSTAT", 2, null);
                ScadaResult scadaResult = JsonUtil.getJsonToBean(realdata, ScadaResult.class);
                if (scadaResult.getCode().equals(0)) {
                    List<ScadaEntity> items = scadaResult.getItems();
                    ScadaEntity scadaEntity = items.get(0);
                    entity.setValue(scadaEntity.getPV());
                    if (scadaEntity.getALMSTAT().equals(0)) {
                        entity.setResult("正常");
                    }else{
                        entity.setResult("异常");
                    }

                }
            }


        }

        return checkTaskPoints;
    }


    /**
     * 判断任务是否需要生成
     *
     * @param timeConfiguration
     * @param today
     * @return
     */
    private boolean isTaskScheduledForToday(CheckPlanTimeEntity timeConfiguration, LocalDate today) {
        LocalDate startDate = timeConfiguration.getDatestart().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate endDate = null == timeConfiguration.getDateend() ? null : timeConfiguration.getDateend().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        // 当前是否在任务开始和结束日期之内
        if (startDate.isAfter(today) || (endDate != null && endDate.isBefore(today))) {
            return false;
        }

        int timeInterval = timeConfiguration.getTimespaced();
        String timeType = timeConfiguration.getTimetype();
        LocalDate taskDate = startDate;

        while (taskDate.isBefore(today) || taskDate.isEqual(today)) {
            //已经结束的任务
            if (endDate != null && taskDate.isAfter(endDate)) {
                return false;
            }
            //今天不需要生成，之后生成
            if (taskDate.isAfter(today)) {
                return false;
            }
            //今天的任务
            if (taskDate.isEqual(today)) {
                return true;
            }
            switch (timeType) {
                case "1":
                    taskDate = taskDate.plusDays(timeInterval);
                    break;
                case "2":
                    taskDate = taskDate.plusWeeks(timeInterval);
                    break;
                case "3":
                    taskDate = taskDate.plusMonths(timeInterval);
                    break;
                // 添加其他类型的处理逻辑
            }
        }

        return false;
    }

    /**
     * 基于需要生成的item任务集合，处理生成数据
     *
     * @param paramList
     */
    private void createTaskForToday(List<Map<String, Object>> paramList) {
        for (Map<String, Object> map : paramList) {
            CheckPlanEntity planEntity = (CheckPlanEntity) map.get("plan");
            List<CheckPlanItemEntity> planItemEntityList = (List<CheckPlanItemEntity>) map.get("items");
            List<CheckPlanTimeEntity> planTimeEntityList = (List<CheckPlanTimeEntity>) map.get("times");
            if (planTimeEntityList != null && planTimeEntityList.size() > 0) {
                for (CheckPlanTimeEntity timeEntity : planTimeEntityList) {

                    //任务表
                    String code = planEntity.getCode();


                    CheckTaskEntity taskEntity = new CheckTaskEntity();
                    taskEntity.setDescription(planEntity.getDescription());
                    taskEntity.setPlanname(planEntity.getName());
                    taskEntity.setPlancode(code);
                    taskEntity.setNeeduser(planEntity.getNeeduser());
                    taskEntity.setNeedtime(planEntity.getNeedtime());
                    taskEntity.setErrormax(planEntity.getErrormax());
                    taskEntity.setErrormin(planEntity.getErrormin());
                    taskEntity.setCheckteam(planEntity.getCheckteam());
                    taskEntity.setFiles(planEntity.getFiles());

                    taskEntity.setCreatortime(new Date());
                    taskEntity.setCreatoruserid("349057407209541");

                    //状态：0未开始、1进行中、2已完成
                    taskEntity.setStatus("0");
                    taskEntity.setItemtotals(planItemEntityList.size());
                    taskEntity.setItemfinisheds(0);
                    taskEntity.setItemanomalys(0);

                    //任务开始时间和结束时间
                    taskEntity.setTaskstarttime(getDateTime(new Date(), timeEntity.getTimestart()));
                    taskEntity.setTaskendtime(getDateTime(new Date(), timeEntity.getTimeend()));
                    taskEntity.setCreatortime(new Date());
                    List<CheckTaskEntity> list = checkTaskService.list(new LambdaQueryWrapper<CheckTaskEntity>()
                            .eq(CheckTaskEntity::getPlancode, code)
                            .eq(CheckTaskEntity::getTaskstarttime, taskEntity.getTaskstarttime())
                            .eq(CheckTaskEntity::getTaskendtime, taskEntity.getTaskendtime()));
                    if (list != null && list.size() > 0) {
                        continue;
                    }
                    //创建任务，生成id
                    try {
                        this.save(taskEntity);
                        //避免无法生成时，增加无效的流水号
                        taskEntity.setCode(generaterSwapUtil.getBillNumber("rwbm", false));
                        this.update(taskEntity.getId(), taskEntity);
                    } catch (Exception e) {
                        log.info("任务已存在，任务编码：{},开始时间：{},结束时间：{}", code, taskEntity.getTaskstarttime(), taskEntity.getTaskendtime());
                        continue;
                    }

                    //巡检项，每个任务都对应相同的巡检项
                    if (planItemEntityList != null && planItemEntityList.size() > 0) {
                        List<CheckTaskItemEntity> taskItemEntityList = new ArrayList<>();
                        for (CheckPlanItemEntity itemEntity : planItemEntityList) {
                            //巡检项
                            CheckTaskItemEntity taskItemEntity = new CheckTaskItemEntity();
                            taskItemEntity.setId(RandomUtil.uuId());
                            taskItemEntity.setParentid(taskEntity.getId());
                            taskItemEntity.setSortcode(itemEntity.getSortcode());
                            taskItemEntity.setCreatoruserid(userProvider.get().getUserId());
                            taskItemEntity.setCreatortime(new Date());
                            taskItemEntity.setType(itemEntity.getType());
                            taskItemEntity.setName(itemEntity.getEquid());
                            taskItemEntity.setPointName(itemEntity.getPointName());
                            taskItemEntity.setCheckId(itemEntity.getCheckid());
                            if (StringUtil.isNotEmpty(itemEntity.getPointMax())) {
                                taskItemEntity.setMax(Double.valueOf(itemEntity.getPointMax()));

                            }
                            if (StringUtil.isNotEmpty(itemEntity.getPointMin())) {
                                taskItemEntity.setMin(Double.valueOf(itemEntity.getPointMin()));
                            }
                            taskItemEntityList.add(taskItemEntity);
                        }
                        //保存
                        checkTaskItemService.saveBatch(taskItemEntityList);
                    }
                }
            }

        }
    }

    private Date getDateTime(Date date, Date time) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");

        String yearMonthDay = new SimpleDateFormat("yyyy-MM-dd").format(date);
        String hourMinute = new SimpleDateFormat("HH:mm").format(time);

        String combined1 = yearMonthDay + " " + hourMinute;

        Date newDate = null;
        try {
            newDate = dateFormat.parse(combined1);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return newDate;

    }


}
